import Vue from 'vue'
import VueRouter from 'vue-router'

/*
 to 和 from 都是一个对象，里面对应的路由的相关信息
to:去哪
from:从哪来
next: 是一个放行函数，调用next()就代表放行，不调用就代表不放行 next('路径')放行到指定路径的路由
*/

// 先创建一个白名单列表，处于这个列表里的直接放行
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

// import login from '@/views/login'
// import register from '@/views/register'
// import layout from '@/views/layout'
// import detail from '@/views/detail'
// import article from '@/views/article'
// import collect from '@/views/collect'
// import like from '@/views/like'
// import user from '@/views/user'

// 路由懒加载的形式（也叫异步组件）
const login = () => import('@/views/login')
const register = () => import('@/views/register')
const layout = () => import('@/views/layout')
const detail = () => import('@/views/detail')
const article = () => import('@/views/article')
const collect = () => import('@/views/collect')
const like = () => import('@/views/like')
const user = () => import('@/views/user')

Vue.use(VueRouter)

const routes = [
// 路由重定向
  { path: '', redirect: '/article' },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      { name: 'article', path: 'article', component: article },
      { name: 'collect', path: 'collect', component: collect },
      { name: 'like', path: 'like', component: like },
      { name: 'user', path: 'user', component: user }
    ]

  },
  { name: 'login', path: '/login', component: login },
  { name: 'register', path: '/register', component: register },
  { name: 'detail', path: '/detail/:id', component: detail }

]

// 实例化路由对象
const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // 这个回调会在你进入到任意路由之前触发
  //  判断要去的路径在不在白名单里
  if (whiteList.includes(to.path)) {
    // 在，直接放行
    next()
  } else {
    // 不在白名单，就要看本地存储里有没有token
    if (getToken()) {
      // 有token
      next()
    } else {
      Toast('请先登录')
      // 没登录放行到登录页
      next('/login')
    }
  }
})

export default router
